package com.im323.ip.impl;

import java.nio.charset.Charset;

import com.im323.common.util.HttpClientUtils;
import com.im323.common.util.IpModel;
import com.im323.common.util.IpUtil;
import com.im323.ip.IpConverter;

public class Ip138Convert extends IpConverter {

	@Override
	public IpModel parse() {
		long sta = System.currentTimeMillis();
		String doGet = HttpClientUtils.doGet(IpUtil.URL_IP138, null, null, Charset.forName("GBK"));
		String startFlag = "<center>";
		String endFlag = "</center>";
		IpModel ipModel = null;
		if (doGet != null && doGet.contains(startFlag)) {
			int startIndex = doGet.indexOf(startFlag) + startFlag.length();
			int endIndex = doGet.indexOf(endFlag);

			String content = doGet.substring(startIndex, endIndex);

			startIndex = content.indexOf("[") + 1;
			String ip = content.substring(startIndex, content.indexOf("]", startIndex));

			startIndex = content.indexOf("来自：", startIndex) + 3;
			String location = content.substring(startIndex, content.indexOf(" ", startIndex));
			String isp = content.substring(content.indexOf(" ", startIndex), content.length());

			ipModel = new IpModel();
			ipModel.setIpAddress(ip);
			ipModel.setLocation(location);
			ipModel.setIsp(isp);
			ipModel.setDelay(System.currentTimeMillis() - sta);
			ipModel.setUrl(IpUtil.URL_IP138);
		}
		return ipModel;
	}

}
